package cn.yr.gateway.filter;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.yr.common.core.constant.CommonConstants;
import cn.yr.common.core.utils.StrUtil;
import cn.yr.common.core.utils.jwt.JwtUtil;
import cn.yr.common.exception.ret.Ret;
import cn.yr.gateway.config.properties.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private IgnoreWhiteProperties ignoreWhite;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (StrUtil.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst(CommonConstants.HEADER);
        if(StrUtil.isEmpty(token)){
            return setUnauthorizedResponse(exchange,"令牌不能为空");
        }
        String uid = JwtUtil.getUid(token);
        if(StrUtil.isEmpty(uid)){
            return setUnauthorizedResponse(exchange,"令牌错误或者已经过期");
        }
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CommonConstants.JWT_USERID, uid).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSONUtil.toJsonStr(Ret.error(msg)).getBytes());
        }));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
